# -*- coding: utf-8 -*-
#===================
# Author: Huang Gang
# Date: 2017-09-19
#===================
import web
import os
import time
import datetime
import config
from bson.objectid import ObjectId

from app.models import users
from app.models import comments
from main import main_session,render

import uuid
import requests
import random
import json
import re
from req import message_code
from utils.log import log

from utils.runpy import execute
from utils.runpy import write_data
from utils.runpy import create_file
from utils.runpy import create_input

from utils.runpy import run_in_docker
from utils.runpy import rerun_in_docker
from utils.get_date import datelist
#session_data = session._initializer

class forget_password:
    def GET(self):
        return render.forget_password()

class index:
    def GET(self):
        strategy_info = config.sjk.strategy_coll.find({}).sort([("total_gain_rate",-1)]).limit(3)
        strategy_info_1 = config.sjk.strategy_coll.find({}).sort([("subscribe_count",-1)]).limit(4)
        strategy_info_2 = config.sjk.strategy_coll.find({}).sort([("total_gain_rate",-1)]) 
        listdate = []
        listdata =[]
        return render.index(strategy_info,strategy_info_1,strategy_info_2)

    def POST(self):
        strategy_info = config.sjk.strategy_coll.find({})
        listdate = []
        listdata = []
        for item in strategy_info[:3]:
            listdate.append(item['list_date'])
            listdata.append(item['list_data'])
        return json.dumps({"listdate":listdate, 'listdata':listdata})

class register:
    def GET(self):
        return render.register()
    def POST(self):
        dic_data=json.loads(web.data())
        log.info("Here register in account")
        input_vcode = dic_data['input_vcode']
        phonenumber = dic_data['phonenumber']
        p_dict= main_session['usrs'].get(phonenumber)
        username = dic_data['username']
        password = dic_data['password']
        password2 = dic_data['password2']
        ischecked = dic_data['ischecked']
        md5_pn = md5(phonenumber)
        md5_pw = md5(password)
        md5_f = md5(md5_pn + md5_pw)
        # If the two psswds does not equal to each other,the user haveto register again
        if p_dict['vcode'] != str(input_vcode):
            #------------------------------
            #if the verifying code is wrong
            #------------------------------
            return json.dumps({"errorcode": 3, "errormessage": "The verifying code is wrong."})
        elif password2 != password:
            return json.dumps({"errorcode": 2, "errormessage": "Passwords are not match!"})
        elif len(password) <6 or len(password)>20 :
            return json.dumps({"errorcode": 4, "errormessage": "Password's length is not in [6-20]!"})
        elif ischecked == False:
            return json.dumps({"errorcode": 5, "errormessage": "You should agree the protocol!"})
        elif config.sjk.user_coll.find({"user_phone": phonenumber}).count() > 0:
            errorcode = 0
            errormessage = "%s already exists." % phonenumber
        else:
            errorcode = 1
            errormessage = "%s not exist." % phonenumber

            config.sjk.user_coll.insert_one(
                {"user_id": username,
                 "user_phone": phonenumber,
                 "user_md5": md5_f
                }
            )
        return json.dumps({"errorcode": errorcode, "errormessage": errormessage})

class login:
    def GET(self):
        return render.login()
    def POST(self):
        a = []
        user_input = web.input()
        md5_pn = md5(user_input['phonenumber'])
        md5_pw = md5(user_input['password'])
        md5_f = md5(md5_pn + md5_pw)

        if not users.verification(user_input['phonenumber'], md5_f):
            #phonenumber or password is not correct. try again.
            return render.login()
        user_phone=user_input["phonenumber"]
        user_doc = config.sjk.user_coll.find({"user_phone": user_input['phonenumber']})
        strategy_info = config.sjk.strategy_coll.find({"user_phone": user_phone},{"_id":1, "strategy_name": 1, 'total_gain':1,'username':1,'strategy_type':1,'subscribe_count':1,'price':1})

        account = user_doc[0]['user_phone']
        u_id = uuid.uuid1()
        main_session['usrs'].update({str(u_id): {'account': account}})
        #log.info("session['usrs'].get(u_id) is: %s" % main_session['usrs'].get(u_id))

        web.setcookie('uid', u_id,7200)
        web.setcookie('phone_id',user_input['phonenumber'],7200)
	log.info("login post seeother")
        raise web.seeother('/personal_center', absolute=True)  # required to change to select right records

class logout:
    #def GET(self):
    #    return render.index()
    def POST(self):
        dic_data = json.loads(web.data())
        account = dic_data['phonenumber']
        u_id = dic_data['uid']
        #log.info("The param uid got: %s" % u_id)
        #log.info("The param account got: %s" % account)
        info = config.sjk.strategy_coll.find({})
        info_1 = config.sjk.strategy_coll.find({})  #todo: need to update
        info_2 = config.sjk.strategy_coll.find({})  #todo: need to update

        isuid = False
        c_uid = web.cookies().get('uid')
        #log.info(" TO LOGOUT::: c_uid  is %s" % c_uid)

        for item in main_session['usrs'].keys():
            if u_id in str(item):
                if c_uid== None:
                    isuid = True
                    web.setcookie('uid', None)
                user_account = main_session['usrs'].get(u_id)
                #log.info("href to logout: user_account is %s" % user_account)
                if user_account['account'] == account:
                    isuid = True
                    web.setcookie('uid', None)
            else:
                pass
        if isuid:
            errorcode = 1
            errormessage = "TOLOGOUT"
            main_session['usrs'].update({u_id: None})
        else:
            errorcode = 0
            errormessage = "KEEPLOGIN"
        return json.dumps({"errorcode": errorcode, "errormessage": errormessage, })

class this_user(object):
    def __init__(self, phonenumber, username, md5):
        self.pn = phonenumber
        self.un = username
        self.md5 = md5

class personal_center:
    def GET(self):
        c_uid = web.cookies().get('uid')
        if c_uid == None or c_uid =="None":
            raise web.seeother('/login')
        c_pid = web.cookies().get('phone_id')
        #=====================================
        #select strategies created by the user
        #=====================================
        strategy_info = config.sjk.strategy_coll.find({"phonenumber":c_pid})
        return render.personal_center(strategy_info)
    def POST(self):
        dic_data = json.loads(web.data())
        uid = dic_data['uid']
        uid =str(uid)
        account = dic_data['phonenumber']
        account = str(account)
        c_uid = web.cookies().get('uid')
        c_pid = web.cookies().get('phone_id')
        strategy_info = config.sjk.strategy_coll.find({"phonenumber":c_pid})

        isuid = False
        for item in main_session['usrs'].keys():
            if c_uid in str(item):
                user_account = main_session['usrs'].get(c_uid)
                if user_account['account'] == account:
                    isuid = True
            else:
                pass
        if isuid:
            return render.personal_center(strategy_info)
        else:
            raise web.seeother("/")

class study:
    def GET(self):
        c_uid = web.cookies().get('uid')
        log.info("web.cookies() for /study: %s " % c_uid)
        if c_uid == None or  c_uid =="None":
            raise web.seeother('/login')

        input = web.input()
        id = input.get('id', None)
        if id == None:
            return render.study("","")
        id=input['id'].strip()
        record = config.sjk.strategy_coll.find({"_id": ObjectId(id)},{"strategy_code":1,"strategy_name":1})
        code =record[0]["strategy_code"]
        name = record[0]["strategy_name"]
        #log.info("In study: strategy_name is:%s" %name)
        return render.study(code,name)
    def POST(self):
        data = web.data()
        dic_data = json.loads(data)
        uid = dic_data['uid']
        uid =str(uid)
        account = dic_data['phonenumber']
        account = str(account)
        c_webpy_session_id = web.cookies().get('webpy_session_id')
        c_uid = web.cookies().get('uid')

        #log.info("session['usrs'] is: %s" % main_session['usrs'])
        #log.info("session['usrs'].keys() is: %s" % main_session['usrs'].keys())
        #log.info("c_uid is: %s" %c_uid)

        isuid = False
        for item in main_session['usrs'].keys():
            if c_uid in str(item):
                user_account = main_session['usrs'].get(c_uid)
                #log.info("href to /study: user_account is %s" % user_account)
                if user_account['account'] == account:
                    isuid = True
            else:
                pass
        if isuid:
            return render.study("","")
        else:
            #==================================================
            #if uid is not equal to web.cookies().get('uid'),
            #return render.index()
            #==================================================
            raise web.seeother("/")

class tactics_detail:
    def GET(self):
        c_uid = web.cookies().get('uid')
        log.info("web.cookies() for /tactics_detail: %s " % c_uid)
        if c_uid == None:
            raise web.seeother('/login')
        input = web.input()
        id=input['id'].strip() # in GET
        #log.info("id : %s" %id)
        strategy_items = config.sjk.strategy_coll.find({"_id": ObjectId(id)})
        comments = config.sjk.comment_coll.find({"strategy_id": id})
        return render.tactics_detail(strategy_items[0], comments)
    def POST(self):
        dic_data = json.loads(web.data())
        id = dic_data['id'] # in POST
        #log.info("id : %s" %id)
        listdate=[]
        listdata=[]
        strategy_item = config.sjk.strategy_coll.find({"_id": ObjectId(id)})
        listdate = strategy_item[0]["list_date"]
        listdata = strategy_item[0]["list_data"]
        return json.dumps({"listdate": listdate, 'listdata': listdata})

class verification:
    def POST(self):
        phone_for_verify = json.loads(web.data())['phonenumber']
        vcode = message_code(phone_for_verify,'register')
        main_session['usrs'].update({phone_for_verify:{'vcode': vcode}})
        #log.info("Sending %s" % phone_for_verify)
        return render.register()

class verification_for_update_password:
    def POST(self):
        phone_for_verify=json.loads(web.data())['phonenumber']
        vcode = message_code(phone_for_verify,'reset')
        main_session['usrs'].update({phone_for_verify:{'vcode': vcode}})
        #log.info("Sending vcode for update_password : %s" % phone_for_verify)
        return render.update_password()

class runcode:
    def GET(self,list_date,list_data):
        return (''), 204
    def POST(self):
        data = web.data()
        dic_data = json.loads(data)
        code = dic_data['code']
        phonenumber = dic_data['phonenumber']
        #===================================================================
        #write_data(code,phonenumber) # write code into the file 'output.py'
        #===================================================================
        write_data(code,phonenumber) 
        create_file("test.py", ("%soutput.py"%phonenumber),phonenumber)

        list_data = []
        list_data_tmp = []
        list_wsvc = []
        list_wsvc_tmp = []

        a = run_in_docker(phonenumber)
        log.info("In runcode, the result of run_in_docker:%s" % a)
        str_line = a.split('[')[-1]
	log.info("str_line: %s" % str_line)
	str_line =str_line.split(']')[0]
        list_data_tmp = str_line.split(',')
	log.info("len(list_data_tmp): %s" % len(list_data_tmp))
	log.info("list_data_tmp[0]and[-1]: %s %s" % (list_data_tmp[0],list_data_tmp[-1]) )

        for i in range(len(list_data_tmp)-1):
            list_data.append(float(list_data_tmp[i]))

        length =len(list_data)
        #log.info("length:%s" % length)
	# format the date
 	end = datetime.datetime.now().strftime('%Y/%m/%d')
	log.info("curent date: %s" % end)

        #===================================
	#to get the arguments for datelist()
        #===================================
	this_y = int(end.split("/")[0])
	this_m = int(end.split("/")[1])
	this_d = int(end.split("/")[2])
	start = datetime.datetime.now() + datetime.timedelta(days=-1*length)
        start = start.strftime('%Y/%m/%d')
        log.info("start: %s" % start)
        start_y = int(start.split("/")[0])
        start_m = int(start.split("/")[1])
        start_d = int(start.split("/")[2])

        #==============
	#run datelist()
        #==============
        list_date = datelist((start_y, start_m, start_d), (this_y, this_m, this_d))

        #========================
	#calculating winning rate, 
        #max retracement rate,etc
        #========================
	str_wsvc = a.split(")\n")[-1]
	#log.info("str_wsvc: %s" % str_wsvc)
        str_wsvc = str_wsvc.split("\n[")[0]
	list_wsvc_tmp = re.split("\n|:", str_wsvc)
	#log.info("list_wsvc_tmp: %s" % list_wsvc_tmp)
        #log.info(len(list_wsvc_tmp)/2)
	p = 0
        transaction_count = len(list_wsvc_tmp)/2
	for i in range(len(list_wsvc_tmp)/2):
            list_wsvc.append(float(list_wsvc_tmp[2*i+1]))
	    if float(list_wsvc_tmp[2*i+1]) >0:
	        p = p + 1
        init_capital = list_data[0]
	winning_rate = float(p) / transaction_count
	max_retracement_rate = (init_capital - min(list_data))/init_capital
        total_gain = list_data[-1]-init_capital
        total_gain_rate = (list_data[-1]-init_capital)/(list_data[0]*length)

        #========
        #log.info
        #========
	#log.info("In runcode,list_wsvc: %s" % list_wsvc)
        #log.info(p)
	#log.info(winning_rate)
	#log.info(max_retracement_rate)
        #log.info(init_capital)
	#log.info(total_gain)
	#log.info(total_gain_rate)

	list_info = [init_capital,transaction_count,winning_rate,max_retracement_rate,total_gain,total_gain_rate]
        result = {"date": list_date, "data": list_data, "info":list_info}
        return json.dumps(result)

class rerun:
    def POST(self):
        dic_data = json.loads(web.data())
        code = dic_data['code']
        init_capital = dic_data['init_capital']
        phonenumber = dic_data['phonenumber']
        #====================================
        #write code into the file 'output.py'
        #====================================
        write_data(code,phonenumber) 

        create_file("test_rerun.py", ("%soutput.py"%phonenumber),phonenumber)
        #========================================
        #create the input file for the simulation 
        #========================================
        create_input(init_capital,"5",phonenumber)

        list_data = []
        list_data_tmp = []
        list_wsvc = []
        list_wsvc_tmp = []

        a = rerun_in_docker(phonenumber)
        log.info("In rerun, the result of run_in_docker:%s" % a)
        str_line = a.split('[')[-1]
	log.info("rerun:str_line: %s" % str_line)
	str_line =str_line.split(']')[0]
        list_data_tmp = str_line.split(',')
	log.info("len(list_data_tmp): %s" % len(list_data_tmp))
	log.info("list_data_tmp[0]and[-1]: %s %s" % (list_data_tmp[0],list_data_tmp[-1]) )

        for i in range(len(list_data_tmp)-1):
            list_data.append(float(list_data_tmp[i]))

        length =len(list_data)
        log.info("rerun: length:%s" % length)
	# format the date
 	end = datetime.datetime.now().strftime('%Y/%m/%d')
	log.info("curent date: %s" % end)

        #===================================
	#to get the arguments for datelist()
        #===================================
	this_y = int(end.split("/")[0])
	this_m = int(end.split("/")[1])
	this_d = int(end.split("/")[2])
	start = datetime.datetime.now() + datetime.timedelta(days=-1*length)
        start = start.strftime('%Y/%m/%d')
        log.info("in account.rerun: start: %s" % start)
        start_y = int(start.split("/")[0])
        start_m = int(start.split("/")[1])
        start_d = int(start.split("/")[2])

        #==============
	#run datelist()
        #==============
        list_date = datelist((start_y, start_m, start_d), (this_y, this_m, this_d))

        #========================
	#calculating winning rate, 
        #max retracement rate,etc
        #========================
	str_wsvc = a.split(")\n")[-1]
	#log.info("str_wsvc: %s" % str_wsvc)
        str_wsvc = str_wsvc.split("\n[")[0]
	list_wsvc_tmp = re.split("\n|:", str_wsvc)
	log.info("list_wsvc_tmp: %s" % list_wsvc_tmp)
        #log.info(len(list_wsvc_tmp)/2)
	p = 0
        transaction_count = len(list_wsvc_tmp)/2
	for i in range(len(list_wsvc_tmp)/2):
            list_wsvc.append(float(list_wsvc_tmp[2*i+1]))
	    if float(list_wsvc_tmp[2*i+1]) >0:
	        p = p + 1
        init_capital = list_data[0]
	winning_rate = float(p) / transaction_count
	max_retracement_rate = (init_capital - min(list_data))/init_capital
        total_gain = list_data[-1]-init_capital
        total_gain_rate = (list_data[-1]-init_capital)/(list_data[0]*length)

	list_info = [init_capital,transaction_count,winning_rate,max_retracement_rate,total_gain,total_gain_rate]
        result = {"date": list_date, "data": list_data, "info":list_info}
        log.info("In rerun: result is obtained.")
        return json.dumps(result)

class update_password:
    def GET(self):
        return render.update_password()
    def POST(self):
        input_vcode = json.loads(web.data())['input_vcode']
        #log.info("input_vcode: %s" % input_vcode)
        phonenumber = json.loads(web.data())['phonenumber']
        p_dict = main_session['usrs'].get(phonenumber)
        #log.info("p_dict %s is:" % p_dict)
        #log.info("p_dict['vcode'] (in db) %s " % p_dict['vcode'])
        if p_dict['vcode'] != str(input_vcode):
            log.info("vcode is not correct.")
            return render.index()
        password = json.loads(web.data())['password']
        password2 = json.loads(web.data())['password2']

        md5_pn = md5(phonenumber)
        md5_pw = md5(password)
        md5_f = md5(md5_pn + md5_pw)

        #===============================================
        #If the username already exists, the reg. fails.
        #===============================================
        if config.sjk.user_coll.find({"user_phone":phonenumber}).count() < 1 or password2 != password:
            log.info("Passwords are not equal")
            return render.update_password()

        config.sjk.user_coll.update(
            {"user_phone": phonenumber},{"$set":{"user_md5": md5_f}}
            )
        #============================
        #can login with new password!
        #============================
        return render.login()

class save_strategy:
    def POST(self):
        dic_data = json.loads(web.data())
        phonenumber= dic_data["phonenumber"]
        strategy_code = dic_data["code"]
        strategy_name = dic_data["strategy_name"]
        if strategy_name.strip()=="":
            return json.dumps({"errorcode": 0, "errormessage": "The strategy name is null."})
        #init_capital = dic_data["init_capital"]
        list_date, list_data,list_info = execute(strategy_code,phonenumber)
        #log.info("list_date: %s list_data: %s" %(list_date, list_data))
        strategy_type = '外汇期货'
        user_info = config.sjk.user_coll.find({"user_phone":phonenumber},{"user_id":1})
        username = user_info[0]["user_id"]
        max_retr = 100*round(list_info[3],5) 
        publish_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        total_gain = round(100*list_info[4])/100
        total_gain_rate = 100*round(list_info[5],5)
        subscribe_count = 0
        price = 5
        init_capital =("%.2f" % list_data[0])
        #inti_capital = ("%.2f"% 10000)
        transaction_count = list_info[1]
        winning_rate = 100*round(list_info[2],5)
        if (config.sjk.strategy_coll.find({"strategy_name": strategy_name}).count() < 1):
            config.sjk.strategy_coll.insert(
                {
                 'strategy_name': strategy_name,
                 'strategy_type': strategy_type,
                 'strategy_code': strategy_code,
                 'phonenumber': phonenumber,
                 'username': username,
                 'publish_time': publish_time,
                 'init_capital': init_capital,
                 'max_retr': max_retr,
                 'total_gain': total_gain,
                 'total_gain_rate': total_gain_rate,
                 'subscribe_count': subscribe_count,
                 'price': price,
                 "list_date": list_date,
                 "list_data": list_data,
                 'transaction_count': transaction_count,
                 'winning_rate': winning_rate
                 }
            )
        else:
            config.sjk.strategy_coll.update(
                {'strategy_name': strategy_name},
                {'$set': {'strategy_code': strategy_code,'list_date': list_date, 'list_data': list_data, 'init_capital': init_capital, 'transaction_count': transaction_count, 'winning_rate': winning_rate, 'max_retr': max_retr, 'total_gain': total_gain, 'total_gain_rate': total_gain_rate}})
        return json.dumps({})

def md5(pwd):
    import hashlib
    m = hashlib.md5()
    m.update(pwd)
    return m.hexdigest()

class save_comment:
    def POST(self):
        dic_data = json.loads(web.data())
        comment_text = dic_data["comment_text"]
        comment_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        strategy_id = dic_data["strategy_id"]
        phonenumber = dic_data["phonenumber"]
        user_info = config.sjk.user_coll.find({"user_phone":phonenumber})
        username = user_info[0]["user_id"]
        if comment_text =="":
            pass
        comments.add_comment(phonenumber, username, strategy_id, comment_text,comment_time)
        return json.dumps({})

import thread
lock = thread.allocate_lock()
class subscribe:
    def POST(self):
        post_data = web.data()
        dic_data = json.loads(post_data)
        phonenumber = dic_data["phonenumber"]
        user_id_0 = config.sjk.user_coll.find({"user_phone":phonenumber})
        user_id =user_id_0[0]["user_id"]
        log.info("user_id is: %s" % user_id)
        strategy_id = dic_data["strategy_id"].strip()
        #log.info("strategy_id is : %s" % strategy_id)
        if config.sjk.subscribe_coll.find({"phonenumber":phonenumber, "strategy_id":strategy_id}).count() >0:
            #log.info("ALready book")
            pass
        else:
            try:
                lock.acquire()
                tmp = config.sjk.strategy_coll.find({"_id": ObjectId(strategy_id)})
                subscribe_count = tmp[0]["subscribe_count"] +1
                log.info("subscribe times: %s" % subscribe_count)
                config.sjk.strategy_coll.update({"_id":ObjectId(strategy_id)},{"$set":{"subscribe_count": subscribe_count}})
                subscribe_info = config.sjk.subscribe_coll.insert({"phonenumber":phonenumber, "strategy_id":strategy_id})
            except Exception:
                pass
            finally:
                lock.release()
        return json.dumps({})

class validation_strategy_name:
    def POST(self):
        log.info("START VALIDATION")
        dic_data = json.loads(web.data())
        value = dic_data["value"]
        #log.info(value)

        if config.sjk.strategy_coll.find({"strategy_name": value}).count()>0:
            errorcode = 0
            errormessage = "%s already exists." % value
        else:
            errorcode = 1
            errormessage = "%s not exist." % value

        #log.info(errormessage)
        return json.dumps({"errorcode":errorcode,"errormessage": errormessage})

class validation_islogin:
    def POST(self):
        #log.info("START VALIDATION_islogin")
        post_data = web.data()
        dic_data = json.loads(post_data)

        uid = dic_data['uid']
        uid =str(uid)
        account = dic_data['phonenumber']
        log.info('In validation_islogin TYPE of account is: %s' % type(account))
        account = str(account)

        c_webpy_session_id = web.cookies().get('webpy_session_id')
        c_uid = web.cookies().get('uid')
        #user_account = main_session['usrs'].get(account)

        log_in = True
        if c_uid in main_session['usrs'].keys():
            user_account = main_session['usrs'].get(c_uid)
            #log.info("validation islogin: user_account is %s" % user_account)
            if user_account == None:
                log_in = False
        else:
            log_in = False

        if log_in:
            errorcode = 1
            errormessage = "%s login." % uid
        else:
            errorcode = 0
            errormessage = "%s not login yet." % uid
        #log.info(errormessage)
        return json.dumps({"errorcode":errorcode,"errormessage": errormessage})

class current_user:
    def POST(self):
        #log.info("START VALIDATION_islogin")
        post_data = web.data()
        dic_data = json.loads(post_data)

        uid = dic_data['uid']
        uid =str(uid)
        account = dic_data['phonenumber']
        #log.info('In validation_islogin TYPE of account is: %s' % type(account))
        account = str(account)

        c_webpy_session_id = web.cookies().get('webpy_session_id')
        c_uid = web.cookies().get('uid')
        #user_account = main_session['usrs'].get(account)

        log_in = True
        if c_uid in main_session['usrs'].keys():
            user_account = main_session['usrs'].get(c_uid)
            #log.info("validation islogin: user_account is %s" % user_account)
            if user_account == None:
                log_in = False
        else:
            log_in = False
        if log_in:
            username = config.sjk.user_coll.find({"user_phone": account},{"user_id": 1})[0]["user_id"]
            log.info("the usename: %s" % username)
        else:
            username=""

        return json.dumps({"username": username,"user_phone":account})

class help:
    def GET(self):

        c_uid = web.cookies().get('uid')
        #log.info("web.cookies() for /personal: %s " % c_uid)
        if c_uid == None or c_uid == "None":
            raise web.seeother('/login')

        return render.help()

    def POST(self):
        c_uid = web.cookies().get('uid')
        log.info("web.cookies() for /personal: %s " % c_uid)
        if c_uid == None or c_uid == "None":
            raise web.seeother('/login')

        data = web.data()
        dic_data = json.loads(data)
        uid = dic_data['uid']
        uid =str(uid)

        account = dic_data['phonenumber']
        #log.info('type of account is %s:' % type(account))
        account = str(account)

        c_uid = web.cookies().get('uid')

        #log.info("session['usrs'] is: %s" % main_session['usrs'])
        #log.info("session['usrs'].keys() is: %s" % main_session['usrs'].keys())
        log.info("c_uid is: %s" %c_uid)
        #log.info("type of c_uid is: %s" % type(c_uid))
        #log.info("type session['usrs'].keys()[0] is: %s" % type(str(main_session['usrs'].keys()[0])))

        islogin = False
        for item in main_session['usrs'].keys():
            if c_uid in str(item):
                user_account = main_session['usrs'].get(c_uid)
                #log.info("href to /study: user_account is %s" % user_account)
                if user_account['account'] == account:
                    islogin = True
            else:
                pass
        if islogin:
            return render.help()
        else:
            log.debug("uid is not equal to web.cookies().get('uid')")
            return render.index()
